package org.example.JwtUtil;



import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.example.dao.entity.User;
import org.example.utils.Base64Example;

import java.util.Date;

public class JwtUtils {
    private final String secretKey;
    private long expirationTime = 7;
    Algorithm algorithm;
    public JwtUtils (String secretKey, long expirationTime) {
        this.secretKey = secretKey;
        this.expirationTime = expirationTime;
        this.algorithm = Algorithm.HMAC256(this.secretKey);
    }
    public JwtUtils (String secretKey) {
        this.secretKey = secretKey;
        this.algorithm = Algorithm.HMAC256(this.secretKey);
    }
    /**
     * 生成 JWT Token
     */
    public  String generateToken(User user) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + this.expirationTime*86400);
String s = JWT.create()
        .withClaim("userId",user.getId())
        .withClaim("userName",user.getNickName())
        .withIssuedAt(now)
        .withExpiresAt(expiryDate)
        .sign(algorithm);
        return Base64Example.StringToBase64(s);
    }

    // 验证 JWT
    public DecodedJWT verifyToken(String token) throws JWTVerificationException {
       String s =  Base64Example.Base64ToString(token);
        return JWT.require(this.algorithm)
                .build()
                .verify(s);  // 如果 token 无效，会抛出异常
    }

    /**
     * 检查 Token 是否过期
     */
    // 从 JWT 中获取用户信息
    public  User getUserInfo(String token) throws JWTVerificationException {
        DecodedJWT decodedJWT = this.verifyToken(token);
        String username = decodedJWT.getClaim("userName").asString();
        String ID = decodedJWT.getClaim("userId").asString();
      User u =   new User();
      u.setNickName(username);
      u.setId(Long.valueOf(ID));
        return u;
    }
}
